package com.ruoyi.wx.controller;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysMenu;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginBody;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.framework.web.service.SysPermissionService;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.service.ISysMenuService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.wx.domain.UserInfo;
import com.ruoyi.wx.domain.WxLoginInfo;
import org.apache.commons.collections.CollectionUtils;
import org.omg.PortableInterceptor.USER_EXCEPTION;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.schema.Collections;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Collection;
import java.util.List;
import java.util.Set;

/**
 * 登录验证
 * 
 * @author ruoyi
 */
@RestController
@RequestMapping("/wx/auth")
public class WechatLoginController
{
    @Autowired
    private SysLoginService loginService;

    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private WxMaService wxService;

    /**
     * 微信登录方法
     * 
     * @param wxLoginInfo 登录信息
     * @return 结果
     */
    @PostMapping("/login_by_weixin")
    public Object loginByWeixin(@RequestBody WxLoginInfo wxLoginInfo, HttpServletRequest request) {
        //wx.login的code,有效期只有五分钟
        String code=wxLoginInfo.getCode();
        UserInfo userInfo = wxLoginInfo.getUserInfo();
        if(StringUtils.isEmpty(code)||userInfo==null){
            return AjaxResult.error("登录失败，请联系管理员！");
        }
        String openId=null;
        String sessionKey=null;
        try{
            WxMaJscode2SessionResult result = this.wxService.getUserService().getSessionInfo(code);
            sessionKey = result.getSessionKey();
            openId = result.getOpenid();
        }catch (Exception e){
            e.printStackTrace();
        }
        if(sessionKey==null||openId==null){
            return AjaxResult.error("登录失败，请联系管理员！");
        }
        SysUser sysUser=new SysUser();
        sysUser.setOpenId(openId);
        List<SysUser> sysUsers = userService.selectUserList(sysUser);
        SysUser user=new SysUser();
        if(CollectionUtils.isNotEmpty(sysUsers)){
            user= sysUsers.get(0);
            user.setUserId(user.getUserId());
            user.setLoginIp(IpUtils.getIpAddr(request));
            user.setSessionKey(sessionKey);
            userService.updateUserProfile(user);
        }else{
            user.setUserName(userInfo.getNickName());
            user.setNickName(userInfo.getNickName());
            user.setPassword(openId);
            user.setOpenId(openId);
            user.setAvatar(userInfo.getAvatarUrl());
            user.setStatus("0");
            user.setSessionKey(sessionKey);
            user.setLoginIp(IpUtils.getIpAddr(request));
            userService.insertUser(user);
        }
        LoginUser loginUser=new LoginUser();
        userInfo.setUserId(user.getUserId());
        userInfo.setNickName(user.getNickName());
        loginUser.setUser(user);
        //生成令牌
        AjaxResult success = AjaxResult.success();
        success.put(Constants.TOKEN, tokenService.createToken(loginUser));
        success.put("userInfo", userInfo);
        return success;
    }

    /**
     * 预留接口，需先认证，缴费300元才能使用，预留手机号码一键登录方法
     *
     * @param wxLoginInfo 登录信息
     * @return 结果
     */
    @PostMapping("/login_by_phone")
    public Object loginByPhone(@RequestBody WxLoginInfo wxLoginInfo, HttpServletRequest request) {
        //wx.login的code,有效期只有五分钟
        String code=wxLoginInfo.getCode();
        UserInfo userInfo = wxLoginInfo.getUserInfo();
        if(StringUtils.isEmpty(code)||userInfo==null){
            return AjaxResult.error("登录失败，请联系管理员！");
        }
        String openId=null;
        String sessionKey=null;
        String phoneNumber=null;
        try{
            WxMaJscode2SessionResult result = this.wxService.getUserService().getSessionInfo(code);
            sessionKey = result.getSessionKey();
            openId = result.getOpenid();
            //获取手机号码
            WxMaPhoneNumberInfo phoneNoInfo = this.wxService.getUserService().getPhoneNoInfo(sessionKey, wxLoginInfo.getEncryptedData(), wxLoginInfo.getIv());
            phoneNumber = phoneNoInfo.getPhoneNumber();
        }catch (Exception e){
            e.printStackTrace();
        }
        if(sessionKey==null||openId==null){
            return AjaxResult.error("登录失败，请联系管理员！");
        }
        SysUser sysUser=new SysUser();
        sysUser.setOpenId(openId);
        List<SysUser> sysUsers = userService.selectUserList(sysUser);
        SysUser user=new SysUser();
        if(CollectionUtils.isNotEmpty(sysUsers)){
            user= sysUsers.get(0);
            user.setUserId(user.getUserId());
            user.setLoginIp(IpUtils.getIpAddr(request));
            user.setSessionKey(sessionKey);
            userService.updateUser(sysUser);
        }else{
            user.setUserName(phoneNumber);
            user.setNickName(userInfo.getNickName());
            user.setPassword(openId);
            user.setPhonenumber(phoneNumber);
            user.setOpenId(openId);
            user.setAvatar(userInfo.getAvatarUrl());
            user.setStatus("0");
            user.setSessionKey(sessionKey);
            user.setLoginIp(IpUtils.getIpAddr(request));
            userService.insertUser(user);
        }
        LoginUser loginUser=new LoginUser();
        loginUser.setUser(user);
        //生成令牌
        AjaxResult success = AjaxResult.success();
        success.put(Constants.TOKEN, tokenService.createToken(loginUser));
        success.put("userInfo", userInfo);
        return success;
    }
}
